$("#close").on("click", () => {
  window.ipcRenderer.send("closeAddServe");
});
$(".open-mic").on("keydown", setKey);
$(".open-voice").on("keydown", setKey);
$(".serve-finish").on("click", finish);
window.ipcRenderer.invoke("isOpenVoice").then((res) => {
  $(".checkbox").prop("checked", res.isOpenVoice);
});
window.ipcRenderer.invoke("getFastKey").then((res) => {
  if (res.voice) {
    $(".open-voice").val(`Control + Alt + ${res.voice}`)
    $(".open-voice").data('key', res.voice)
  };
  if (res.mic){
    $(".open-mic").val(`Control + Alt + ${res.mic}`)
    $(".open-mic").data('key', res.mic)
  };
  if (res.username) {
    $(".username").val(res.username)
  };
});
function setKey(e) {
  e.preventDefault();
  if (
    e.key === "Control" ||
    e.key === "Alt" ||
    e.key === "Shift" ||
    e.key === " "
  )
    return;
  if (e.key === "Escape") {
    $(e.target).data("key", null);
    $(e.target).val(null);
  } else {
    $(e.target).data("key", e.key);
    $(e.target).val(`Control + Alt + ${e.key}`);
  }
}
const toolChannel = new BroadcastChannel("toolChannel");
async function finish() {
  const resVoice = await sendKey(".open-voice");
  if (!resVoice)
    return $(".open-voice").parent().siblings("p").css({ opacity: 1 });
  $(".open-voice").parent().siblings("p").css({ opacity: 0 });
  const resmic = await sendKey(".open-mic");
  if (!resmic) return $(".open-mic").parent().siblings("p").css({ opacity: 1 });
  $(".open-mic").parent().siblings("p").css({ opacity: 0 });
  const isOpenVoice = $(".checkbox").prop("checked");
  const username = $(".username").val().trim() ? $(".username").val() : null;
  toolChannel.postMessage({ isOpenVoice, username });
  window.ipcRenderer.invoke("isOpenVoice", { isOpenVoice, username });
  window.ipcRenderer.send("closeAddServe");
}

async function sendKey(dom) {
  return await window.ipcRenderer.invoke("sendKey", {
    key: $(dom).data("key"),
    type: $(dom).data("text"),
  });
}
